package com.shanyepifu.client;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.InetAddress;
import java.net.Socket;

/**
 * Created by lifaxin on 16/7/18.
 */
public class RPCRefer {

    public <T> T refer(Class<T> targetInter, InetAddress inetAddress, int port) throws Exception {

        // 代理类实现
        T target = (T) Proxy.newProxyInstance(targetInter.getClassLoader(), new Class<?>[]{targetInter}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Socket socket = new Socket(inetAddress, port);
                ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                oos.writeUTF(method.getName());
                oos.writeObject(method.getParameterTypes());
                oos.writeObject(args);
                ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                Object result = ois.readObject();
                if (result instanceof Throwable) {
                    throw (Throwable) result;
                }
                return result;
            }
        });
        return target;
    }
}
